var crypto = require('crypto');
var User = require('../models/user.js')
var Report = require('../models/report.js');
var url = require('url');
var querystring = require('querystring');
module.exports = function (app) { 
	  
	app.get('/', function (req, res) { 
		Report.get(null, 1, function(err, reports) {
			if(err) {
				reports = [];
			}
			if (req.session.user){
				res.render('index', {
					title: '首页',
					reports: reports
				});
			}else{
				res.render('index', {
					title: '首页'
				});
			}
		});
	});
	app.use(function (req, res){
		res.render("404");
	});
	app.get('/reg', checkNotLogin);
	app.get('/reg', function (req, res) { 
		console.log('get /reg');
		res.render('reg', {title: '用户注册'}); 
	}); 
	app.post('/reg', checkNotLogin);
	app.post('/reg',function(req,res){
		console.log('post /reg');
		if(req.body['password_re'] != req.body['password']){
			req.flash('error','密码和确认密码不一致');
			console.log('密码和确认密码不一致');
			return res.redirect('/reg');
		} 
		var md5 = crypto.createHash('md5');
		var password = md5.update(req.body.password).digest('base64');
		var newUser = new User({
			name:req.body.username,
			password:password,
		});
		User.get(newUser.name,function(err,user){
			if(user)
				err = '用户名已经存在';
			if(err){
				req.flash('error',err);
				console.log(err);
				return res.redirect('/reg');
			}
			newUser.save(function(err){
				if(err){
					req.flash('error',err);
					console.log(err);
					return res.redirect('/reg');
				}
				 req.session.user = newUser;
				 req.flash('success','注册成功');
				 console.log('注册成功');
				 res.redirect('/');
			});
		});
	});
	app.get('/login', checkNotLogin);
	app.get('/login',function(req,res){
		res.render('login',{title:'用户登录'})
	});
	app.post('/login', checkNotLogin);
	app.post('/login', function(req, res) {
        var md5 = crypto.createHash('md5');
        console.log('username='+req.body.username);
        if(req.body.username == '' || req.body.password == ''){
        	req.flash('error', '请输入用户名或密码');
            return res.redirect('/login');
        }
        var password = md5.update(req.body.password).digest('base64');

        User.get(req.body.username, function(err, user) {
            if (!user) {
                req.flash('error', '用户不存在');
                return res.redirect('/login');
            }
            if (user.password != password) {
                req.flash('error', '密码输入错误');
                return res.redirect('/login');
            }
            req.session.user = user;
            req.flash('success', '登录成功');
            res.redirect('/');
        });
    });
	
	 app.get('/logout', checkLogin);
	 app.get('/logout', function(req, res) {
	        req.session.user = null;
	        req.flash('success', '退出成功');
	        res.redirect('/');
	    });
	 
	app.post('/verifyUser', function(req, res, next) {
		res.header('Content-Type', 'text/plain');
		User.get(req.body.username, function(err, user) {
			var isExists='false';
			if (user) {
				isExists = 'true';
			}
			res.end(isExists)
       });
	});
	
	app.post('/report', checkLogin);
	app.post('/report', function(req, res) {
		console.log('Get URL==============='+req.headers['referer']);
        var currentUser = req.session.user;
        var report = new Report(currentUser.name, req.body.report);
        console.log(report);
        report.save(function(err) {
            if (err) {
            req.flash('error', err);
            return res.redirect(req.headers['referer']);
        }
        //req.flash('success', 'Report success');
        //res.redirect('/u/' + currentUser.name);
        res.redirect(req.headers['referer']);
        });
    });

    function checkLogin(req, res, next) {
        if (!req.session.user) {
            req.flash('error', '您还没有没有登录');
            return res.redirect('/login');
        }
        next();
    }
    function checkNotLogin(req, res, next) {
        if (req.session.user) {
            req.flash('error', '请登录');
            return res.redirect('/');
        }
        next();
    }
    
    app.get('/u/:user', function(req, res) {
    	console.log('./u/user');
        User.get(req.params.user, function(err, user) {
            if (!user) {
                req.flash('error', '用户不存在');
                return res.redirect('/');
            }
            //var arg = url.parse(req.url).query; 
            //var page = querystring.parse(arg).page;
            var page = req.query.page ? parseInt(req.query.page) : 1;
            console.log(page);
            Report.get(user.name, page, function(err, reports, count) {
                if (err) {
                    req.flash('error', err);
                    return res.redirect('/');
                }
                var totalPage = (count%10 == 0) ? (count/10) : (count/10 + 1);
                console.log('count='+count+'	totalPage='+totalPage);
                res.render('user', {
                    title: user.name,
                    reports: reports,
                    currentPage: page,
                    totalPages: totalPage
                });
            });
        });
    });
}	